package com.situ.company.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.situ.company.entity.Employee;

// /*代表拦截所有的请求
@WebFilter(filterName = "loginFilter", urlPatterns = {"/*"})
public class LoginFilter implements Filter{

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		System.out.println("LoginFilter.init()");
	}

	// 在访问所有的请求之前，都会首先经过Filter里面这个doFilter判断是否登录
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		System.out.println("LoginFilter.doFilter()");
		
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		// 获得请求的路径
		String servletPath = httpServletRequest.getServletPath();
		System.out.println("servletPath: " + servletPath);
		// 对于和登录相关的就不去判断是否登录
		// js/css/png也是不拦截
		if ("/web/login.jsp".equals(servletPath) 
				|| "/loginServlet".equals(servletPath)
				|| servletPath.endsWith(".js")
				|| servletPath.endsWith(".css")
				|| servletPath.endsWith(".png")) {
			// 放行，继续下一个Filter或者Servlet
			chain.doFilter(request, response);
		} else {
			// HttpSession 存放在服务器的一块内存区域，是属于每个用户，如果已经的Employee就把
			// Employee的信息放到Session，根据这个来判断用户是否已经登录
			HttpSession session = httpServletRequest.getSession();
			Employee employee = (Employee) session.getAttribute("employee");
			if (employee == null) {// 代表用户没有登录
				// 重定向到登录界面，让用户登录
				httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + "/web/login.jsp");
				return;
			}
			// 如果已经登录要放行，放行，继续下一个Filter或者Servlet
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {
		System.out.println("LoginFilter.destroy()");
	}

}
